package com.example.baimao_tp.ui.screen

import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.KeyboardArrowDown
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import com.example.baimao_tp.R
import com.example.baimao_tp.data.PoseConfigManager
import com.example.baimao_tp.data.model.PoseItem
import com.example.baimao_tp.viewmodel.CameraViewModel
import android.util.Log

@Composable
fun SettingsScreen(
    viewModel: CameraViewModel = viewModel(),
    onBack: () -> Unit = {},
    languageKey: Int = 0
) {
    val context = LocalContext.current
    val selectedLanguage = viewModel.selectedLanguage
    val selectedLocation = viewModel.selectedLocation
    val selectedModel = viewModel.selectedModel
    val selectedStyle = viewModel.selectedStyle
    val availablePoses = viewModel.availablePoses

    // 加载姿势配置
    LaunchedEffect(Unit) {
        if (!PoseConfigManager.isConfigLoaded()) {
            viewModel.loadPoseConfig(context)
        }
    }

    Column(
        modifier = Modifier
            .fillMaxSize()
            .background(Color.White)
    ) {
        // 使用languageKey来强制重组界面
        LaunchedEffect(languageKey) {
            Log.d("SettingsScreen", "界面重组，languageKey: $languageKey")
        }
        // Header with back button
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(horizontal = 16.dp, vertical = 32.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Icon(
                imageVector = Icons.Default.ArrowBack,
                contentDescription = stringResource(R.string.back),
                modifier = Modifier
                    .size(24.dp)
                    .clickable { onBack() },
                tint = Color.Black
            )
            Text(
                text = stringResource(R.string.settings_title),
                fontSize = 18.sp,
                fontWeight = FontWeight.SemiBold,
                color = Color.Black,
                modifier = Modifier.weight(1f).wrapContentWidth(Alignment.CenterHorizontally)
            )
            Spacer(modifier = Modifier.size(24.dp))
        }

        // Content
        Column(
            modifier = Modifier
                .fillMaxSize()
                .verticalScroll(rememberScrollState())
                .padding(16.dp)
        ) {
            // Language section
            Text(
                text = stringResource(R.string.language),
                fontSize = 14.sp,
                fontWeight = FontWeight.Medium,
                color = Color.Gray,
                modifier = Modifier.padding(bottom = 12.dp)
            )

            // Language dropdown
            LanguageDropdown(
                selectedLanguage = selectedLanguage,
                onLanguageSelected = { language ->
                    viewModel.setLanguage(language, context)
                },
                modifier = Modifier.padding(bottom = 24.dp)
            )

            // Location section
            Text(
                text = stringResource(R.string.location),
                fontSize = 14.sp,
                fontWeight = FontWeight.Medium,
                color = Color.Gray,
                modifier = Modifier.padding(bottom = 12.dp)
            )

            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(bottom = 24.dp),
                horizontalArrangement = Arrangement.spacedBy(12.dp)
            ) {
                SelectionButton(
                    text = stringResource(R.string.outdoor),
                    isSelected = selectedLocation == "Outdoor",
                    modifier = Modifier.weight(1f),
                    onClick = { viewModel.setLocation("Outdoor") }
                )
                SelectionButton(
                    text = stringResource(R.string.indoor),
                    isSelected = selectedLocation == "Indoor",
                    modifier = Modifier.weight(1f),
                    onClick = { viewModel.setLocation("Indoor") }
                )
            }

            // Model section
            Text(
                text = stringResource(R.string.model),
                fontSize = 14.sp,
                fontWeight = FontWeight.Medium,
                color = Color.Gray,
                modifier = Modifier.padding(bottom = 12.dp)
            )

            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(bottom = 24.dp),
                horizontalArrangement = Arrangement.spacedBy(12.dp)
            ) {
                SelectionButton(
                    text = stringResource(R.string.male),
                    isSelected = selectedModel == "Male",
                    modifier = Modifier.weight(1f),
                    onClick = { viewModel.setModel("Male") }
                )
                SelectionButton(
                    text = stringResource(R.string.female),
                    isSelected = selectedModel == "Female",
                    modifier = Modifier.weight(1f),
                    onClick = { viewModel.setModel("Female") }
                )
            }

            // Style section
            Text(
                text = stringResource(R.string.style),
                fontSize = 14.sp,
                fontWeight = FontWeight.Medium,
                color = Color.Gray,
                modifier = Modifier.padding(bottom = 12.dp)
            )

            // 使用配置文件中的姿势选项（单选）
            val stylePairs: List<Pair<String, String>> = availablePoses.map { pose ->
                val displayName = when (selectedLanguage.lowercase()) {
                    "en", "english" -> pose.en
                    "zh", "chinese", "cn" -> pose.cn
                    else -> pose.cn
                }
                Pair(displayName, pose.value)
            }
            val styleRows: List<List<Pair<String, String>>> = stylePairs.chunked(2)

            styleRows.forEach { row ->
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(bottom = 12.dp),
                    horizontalArrangement = Arrangement.spacedBy(12.dp)
                ) {
                    row.forEach { (styleName: String, styleValue: String) ->
                        SelectionButton(
                            text = styleName,
                            isSelected = selectedStyle == styleValue,
                            modifier = Modifier.weight(1f),
                            onClick = {
                                Log.d("SettingsScreen", "选择姿势: $styleName (value: $styleValue)")
                                viewModel.setStyle(styleValue)
                                Log.d("SettingsScreen", "姿势选择已更新: $styleName，返回拍摄界面时将自动应用筛选条件")
                            }
                        )
                    }
                    // Add empty spacer if row has only one item
                    if (row.size == 1) {
                        Spacer(modifier = Modifier.weight(1f))
                    }
                }
            }

            Spacer(modifier = Modifier.height(20.dp))

            // 提示信息
            Text(
                text = stringResource(R.string.filter_apply_hint),
                fontSize = 12.sp,
                color = Color.Gray,
                modifier = Modifier.padding(bottom = 16.dp)
            )

            Spacer(modifier = Modifier.height(20.dp))

            // Generate Poses button
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(48.dp)
                    .clip(RoundedCornerShape(12.dp))
                    .background(Color(0xFF0099FF))
                    .clickable {
                        Log.d("SettingsScreen", "点击生成姿势按钮")
                        Log.d("SettingsScreen", "当前选择: 地点=${selectedLocation}, 模特=${selectedModel}, 姿势=${selectedStyle}")

                        // 调用生成姿势功能，数据加载完成后自动返回拍摄界面
                        viewModel.generatePoses {
                            // 生成完成后返回拍摄界面
                            onBack()
                        }
                    },
                contentAlignment = Alignment.Center
            ) {
                Text(
                    text = stringResource(R.string.generate_poses),
                    fontSize = 16.sp,
                    fontWeight = FontWeight.SemiBold,
                    color = Color.White
                )
            }

            Spacer(modifier = Modifier.height(40.dp))
        }
    }
}

@Composable
private fun LanguageDropdown(
    selectedLanguage: String,
    onLanguageSelected: (String) -> Unit,
    modifier: Modifier = Modifier
) {
    val expanded = remember { mutableStateOf(false) }
    val languages = listOf(
        "en" to "English",
        "zh" to "中文"
    )

    val selectedLanguageText = languages.find { it.first == selectedLanguage }?.second ?: "English"

    Box(modifier = modifier.fillMaxWidth()) {
        OutlinedTextField(
            value = selectedLanguageText,
            onValueChange = { },
            readOnly = true,
            trailingIcon = {
                IconButton(onClick = { expanded.value = true }) {
                    Icon(
                        imageVector = Icons.Default.KeyboardArrowDown,
                        contentDescription = "Dropdown"
                    )
                }
            },
            modifier = Modifier
                .fillMaxWidth()
                .clickable { expanded.value = true },
            shape = RoundedCornerShape(12.dp),
            colors = OutlinedTextFieldDefaults.colors(
                unfocusedBorderColor = Color(0xFFE0E0E0),
                focusedBorderColor = Color(0xFF0099FF)
            )
        )

        DropdownMenu(
            expanded = expanded.value,
            onDismissRequest = { expanded.value = false },
            modifier = Modifier.fillMaxWidth(0.9f)
        ) {
            languages.forEach { (code, name) ->
                DropdownMenuItem(
                    text = {
                        Text(
                            text = name,
                            fontSize = 16.sp,
                            color = if (code == selectedLanguage) Color(0xFF0099FF) else Color.Black
                        )
                    },
                    onClick = {
                        onLanguageSelected(code)
                        expanded.value = false
                    },
                    modifier = Modifier.fillMaxWidth()
                )
            }
        }
    }
}

@Composable
private fun SelectionButton(
    text: String,
    isSelected: Boolean,
    modifier: Modifier = Modifier,
    onClick: () -> Unit = {}
) {
    Box(
        modifier = modifier
            .height(40.dp)
            .clip(RoundedCornerShape(20.dp))
            .background(
                if (isSelected) Color.White else Color(0xFFF0F0F0)
            )
            .border(
                width = if (isSelected) 2.dp else 0.dp,
                color = if (isSelected) Color(0xFF0099FF) else Color.Transparent,
                shape = RoundedCornerShape(20.dp)
            )
            .clickable { onClick() },
        contentAlignment = Alignment.Center
    ) {
        Text(
            text = text,
            fontSize = 14.sp,
            fontWeight = FontWeight.Medium,
            color = if (isSelected) Color(0xFF0099FF) else Color.Gray
        )
    }
}
